package com.zwx.springboot.common.util;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 描述：String类的辅助工具类
 * 
 * @author jaryn
 * 创建时间 2011-4-19
 */
public class StringTools {
	/**
	 * 功能：判断字符串是否为空(null或"") 
	 * @param inputs
	 * @return
	 */
	public static boolean isEmpty(String... inputs){
		for (String s : inputs) 
	      if (s==null || s.equals(""))return true;
	    return false;
	}
	/**
	 * 功能：判断字符串是否不为空(null或"") 
	 * @param inputs
	 * @return
	 */
	public static boolean isNotEmpty(String... inputs){
		for (String s : inputs) 
			if (s==null || s.equals(""))return false;
		return true;
	}
	/**
	 * 功能：判断字符串是否为空(null或""或"   ") 
	 * @param inputs
	 * @return
	 */
	public static boolean isBlank(String... inputs){
		for (String s : inputs)
			if (s==null || s.equals("") || s.trim().equals(""))return true;
	    return false;
	}
	/**
	 * 功能：判断字符串是否不为空(null或""或"   ") 
	 * @param inputs
	 * @return
	 */
	public static boolean isNotBlank(String... inputs){
		for (String s : inputs)
			if (s==null || s.equals("") || s.trim().equals(""))return false;
		return true;
	}
	/**
	 * 功能：正则表达式进行验证
	 * @param input
	 * @param regex
	 * @return
	 */
	public static boolean isMatch(String input,String regex){
		Pattern p = Pattern.compile(regex,Pattern.DOTALL);
		return p.matcher(input).matches();
	}
	/**
	 * 功能：正则表达式进行快速查找
	 * @param input
	 * @param regex
	 * @return
	 */
	public static String match(String input,String regex){
		Pattern p = Pattern.compile(regex,Pattern.DOTALL);
		Matcher matcher = p.matcher(input);
		if (matcher.find()) {
			return matcher.group();
		}
		return null;
	}
	/**
	 * 功能：正则表达式进行快速查找
	 * @param input
	 * @param regex
	 * @param group
	 * @return
	 */
	public static String match(String input,String regex,int group){
		Pattern p = Pattern.compile(regex,Pattern.DOTALL);
		Matcher matcher = p.matcher(input);
		if (matcher.find()) {
			return matcher.group(group);
		}
		return null;
	}
	/**
	 * 功能：正则表达式进行快速查找
	 * @param input
	 * @param regex
	 * @return
	 */
	public static List<String> matchs(String input,String regex){
		Pattern p = Pattern.compile(regex,Pattern.DOTALL);
		Matcher matcher = p.matcher(input);
//		String repStr = matcher.replaceAll("0");
		List<String> list = new ArrayList<String>();
		if (matcher.find()) {
			list.add( matcher.group());
		}
		return list;
	}
	private static Hashtable<String, String> temTable = new Hashtable<String, String>();
	/**
	 * 功能：搜索并替换可能重复的项
	 * @param input
	 * @param regex
	 * @return
	 */
	public static String matchsAndReplaceAll(String input,String regex){
		Pattern p = Pattern.compile(regex,Pattern.DOTALL);
		Matcher matcher;
		while((matcher=p.matcher(input)).find()) {
			String uid = genUniqueId();
			String value = matcher.group();
			String _value = shiftMetaCharacters(value);
			temTable.put(uid, value);
//			System.out.println(_value);
			input = input.replaceAll(_value, uid);
		}
		return input;
	}
	/**
	 * 功能：搜索并替换可能重复的项
	 * @param input
	 * @param regex
	 * @return
	 */
	public static String matchsAndReplaceAll_noPut(String input,String regex){
		Pattern p = Pattern.compile(regex,Pattern.DOTALL);
		Matcher matcher;
		while((matcher=p.matcher(input)).find()) {
			String uid = genUniqueId();
			String value = matcher.group();
			String _value = shiftMetaCharacters(value);
//			temTable.put(uid, value);
//			System.out.println(_value);
			input = input.replaceAll(_value, uid);
		}
		return input;
	}
	/**
	 * 功能：还原所有键值对
	 * @param input
	 * @return
	 */
	public static String restore(String input){
		for (String uid : temTable.keySet()) {
			input = input.replace(uid, temTable.get(uid));
		}
		temTable.clear();
		return input;
	}
	/**
	 * 功能：正则表达式替换
	 * @param input
	 * @param regex
	 * @return
	 */
	public static String replaceAll(String input,String regex,String rep){
		Pattern p = Pattern.compile(regex,Pattern.DOTALL);
		Matcher matcher = p.matcher(input);
		return matcher.replaceAll(shiftReplace(rep));
	}
	/**
	 * 功能：是否为int类型
	 * @param input
	 * @return
	 */
	public static boolean isInt(String input){
	    try{
	      Integer.parseInt(input);
	    }catch (Exception e) {
	      return false;
	    }
	    return true;
	}
	/**
	 * 功能：让字符串首字母大写
	 * @param input
	 * @return
	 */
	public static String toUpperFristCase(String input){
		if (isEmpty(input)) return input;
		return input.replaceAll("^[a-z]", input.substring(0,1).toUpperCase());
	}
	/**
	 * 功能：让字符串首字母小写
	 * @param input
	 * @return
	 */
	public static String toLowerFristCase(String input){
		if (isEmpty(input)) return input;
		return input.replaceAll("^[A-Z]", input.substring(0,1).toLowerCase());
	}
	/**
	 * 功能：字符串数组拼接
	 * @param arrayStr
	 * @param joinStr
	 * @return
	 */
	public static String join(String[] arrayStr,String joinStr){
		if (arrayStr==null)	return null;
		if (joinStr==null)joinStr=" ";
		StringBuffer retStr = new StringBuffer();
		for (int i = 0; i < arrayStr.length-1; i++) {
			retStr.append(arrayStr[i]);
			retStr.append(joinStr);
		}
		retStr.append(arrayStr[arrayStr.length-1]);
		return retStr.toString();
	}
	/**
	 * 功能：字符串转码
	 * @param input
	 * @param sourceEncoding
	 * @param tagetEncoding
	 * @return
	 */
	public static String changeEncoding(String input,String sourceEncoding,String tagetEncoding){
		if(isEmpty(input))return input;
		String retString = null;
		try {
			byte[] bs = input.getBytes(sourceEncoding);
			retString = new String(bs,tagetEncoding);
		} catch (UnsupportedEncodingException e) {
			System.err.println(StringTools.format("[字符串转码失败!]参数:input.length()={0},sourceEncoding={1},tagetEncoding={2}", input.length()+"",sourceEncoding,tagetEncoding ));
			e.printStackTrace();
		}
		return retString;
	}
	/**
	 * 功能：替换多余字符串
	 * @param input
	 * @param len
	 * @param encoding
	 * @return
	 */
	public static String replaceSpilth(String input,int len,String encoding){
		if(isEmpty(input))return input;
		String view = null;   
		int counterOfDoubleByte = 0;   
		byte b[];   
		try {   
			b = input.getBytes(encoding);
			if (b.length <= len) return input;
			for (int i = 0; i < len; i++) {   
				if (b[i] > 0) counterOfDoubleByte++;   
			}   
			if (counterOfDoubleByte % 2 == 0) view = new String(b, 0, len, encoding) + "...";   
			else view = new String(b, 0, len - 1, encoding) + "...";   
		} catch (Exception e) {
			System.err.println(StringTools.format("[替换多余字符串失败!]参数:input.length()={0},len={1},encoding={2}", input.length()+"",len+"",encoding ));
			e.printStackTrace();
		}   
		return view;   
	}
	/**
	 * 功能：过滤HTML标签元素"<",">"," ","&"等等
	 * @param input
	 * @return
	 */
	public static String filterHtml(String input){
		if(isEmpty(input))return input;
		input = input.replaceAll("&", "&amp;");
		input = input.replaceAll("<", "&lt;");
		input = input.replaceAll(">", "&gt;");
		input = input.replaceAll(" ", "&nbsp;");
		input = input.replaceAll("'", "&#39;");
		input = input.replaceAll("\\\\","&quot;");
		input = input.replaceAll("\\n", "<br>");
		return input;
	}
	/**
	 * 功能：转义路径，如将D:\a\b.txt转义成D:\\a\\b.txt
	 * @param path
	 * @return
	 */
	public static String shiftPath(String path){
		if(isEmpty(path))return path;
		path = path.replaceAll("/","\\\\");
		path = path.replaceAll("\\\\", "\\\\\\\\");
		return path;
	}
	/**
	 * 功能：转义路径，如将D:\a\b.txt转义成D:\\a\\b.txt
	 * @param replace
	 * @return
	 */
	public static String shiftReplace(String replace){
		if(isEmpty(replace))return replace;
		replace = replace.replaceAll("\\\\", "\\\\\\\\");
		return replace;
	}
	/**
	 * 功能：转义$-->\$
	 * @param replace
	 * @return
	 */
	public static String shift$(String replace){
		if(isEmpty(replace))return replace;
		replace = replace.replaceAll("\\$", "\\\\\\$");
		return replace;
	}
	/**
	 * 功能：转义元字符,就是把某些正则表达式识别的字符前面加\
	 * @param input 
	 * @return 
	 */
	public static String shiftMetaCharacters(String input){
		input = input.replaceAll("\\\\", "\\\\\\\\");
		input = input.replaceAll("\\.", "\\\\.");
		input = input.replaceAll("\\^", "\\\\^");
		input = input.replaceAll("\\$", "\\\\$");
		input = input.replaceAll("\\*", "\\\\*");
		input = input.replaceAll("\\+", "\\\\+");
		input = input.replaceAll("\\?", "\\\\?");
		input = input.replaceAll("\\{", "\\\\{");
		input = input.replaceAll("\\}", "\\\\}");
		input = input.replaceAll("\\(", "\\\\(");
		input = input.replaceAll("\\)", "\\\\)");
		input = input.replaceAll("\\[", "\\\\[");
		input = input.replaceAll("\\]", "\\\\]");
		input = input.replaceAll("\\|", "\\\\|");
		return input;
	}
	/**
	 * 功能：反转字符串
	 * @param input
	 * @return
	 */
	public static String reverse(String input){
		return new StringBuffer(input).reverse().toString();
	}
	/**
	 * 格式化字符串，如format("{0}={1}","a","b") ==> a=b
	 * @param fmtStr
	 * @param args
	 * @return
	 */
	public static String format(String fmtStr, String... args){
		//fmtStr = shiftMetaCharacters(fmtStr);
		for (int i = 0; i < args.length; i++) {
			fmtStr = fmtStr.replaceAll("\\{"+i+"\\}", shift$(shiftReplace(args[i])));
		}
		return fmtStr;
	}
	/**
	 * 功能：字符串转int类型
	 * @param input
	 * @return
	 */
	public static int toInt(String input){
		try {
			return Integer.parseInt(input);
		} catch (Exception e) {
//			throw new RuntimeException("字符串转int类型失败");
//			System.err.println(StringTools.format("[替换多余字符串失败!]参数:input.length()={0},len={1},encoding={2}", input.length()+"",len+"",encoding ));
//			e.printStackTrace();
			return 0;
		}
	}
	/**
	 * 功能：截取某两个字符串中间的字符串
	 * @param input
	 * @param leftStr
	 * @param rightStr
	 * @return
	 */
	public static String subMid(String input,String leftStr,String rightStr){
		if(isEmpty(input,leftStr,rightStr))return input;
		int left = input.indexOf(leftStr);
		if (left==-1)return input;
		else left += leftStr.length();
		int right = input.indexOf(rightStr,left);
		if (right == -1) return input;
		String retString = input.subSequence(left, right).toString();
		return retString;
	}
	/**
	 * 功能：截取某两个字符串中间的字符串，最后面一个
	 * @param input
	 * @param leftStr
	 * @param rightStr
	 * @return
	 */
	public static String subMidLast(String input,String leftStr,String rightStr){
		if(isEmpty(input,leftStr,rightStr))return input;
		int right = input.lastIndexOf(rightStr);
		if (right == -1) return input;
		int left = input.lastIndexOf(leftStr,right);
		if (left==-1) return input;
		else left += leftStr.length();
		String retString = input.subSequence(left, right).toString();
		return retString;
	}
	/**
	 * 功能：截取某两个字符串中间的所有匹配的字符串，截成数组
	 * @param input
	 * @param leftStr
	 * @param rightStr
	 * @return
	 */
	public static String[] subMids(String input,String leftStr,String rightStr){
		if(isEmpty(input,leftStr,rightStr)) return null;
		String left = "(?<=" +shiftMetaCharacters(leftStr)+ ")";
		String right = "(?=" +shiftMetaCharacters(rightStr)+ ")";
		Pattern p = Pattern.compile(left+".*?"+right,Pattern.DOTALL);
		Matcher m = p.matcher(input);
		List<String> list = new ArrayList<String>();
		while(m.find()){
			String group = m.group();
			list.add(group);
		}
		return list.toArray(new String[list.size()]);
	}
	/**
	 * 功能：截取某个字符串左边的部分，例 D:\a\bb.txt ==> \左边D:
	 * @param input
	 * @param leftStr
	 * @return
	 */
	public static String subLeft(String input,String leftStr){
		if(isEmpty(input,leftStr)) return input;
		int left = input.indexOf(leftStr);
		if (left==-1)return null;
		String retString = input.substring(0,left);
		return retString;
	}
	/**
	 * 功能：截取某个字符串左边更多的部分，例 D:\a\bb.txt ==> \左边D:\a
	 * @param input
	 * @param leftStr
	 * @return
	 */
	public static String subLeftMore(String input,String leftStr){
		if(isEmpty(input,leftStr)) return input;
		int left = input.lastIndexOf(leftStr);
		if (left==-1)return null;
		String retString = input.substring(0,left);
		return retString;
	}
	/**
	 * 功能：截取某个字符串右边的部分，例 D:\a\bb.txt ==> \右边bb.txt
	 * @param input
	 * @param rightStr
	 * @return
	 */
	public static String subRight(String input,String rightStr){
		if(isEmpty(input,rightStr)) return input;
		int right = input.lastIndexOf(rightStr);
		if (right==-1)return null;
		else right = right+rightStr.length();
		String retString = input.substring(right);
		return retString;
	}
	/**
	 * 功能：截取某个字符串右边更多的部分，例 D:\a\bb.txt ==> \右边a\bb.txt
	 * @param input
	 * @param rightStr
	 * @return
	 */
	public static String subRightMore(String input,String rightStr){
		if(isEmpty(input,rightStr)) return input;
		int right = input.indexOf(rightStr);
		if (right==-1)return null;
		else right = right+rightStr.length();
		String retString = input.substring(right);
		return retString;
	}
	
	/**
	 * 功能：字符串转16进制串，to16String("abc") ==> 61:62:63
	 * @param input
	 * @return
	 */
	public static String to16String(String input){
		if (isEmpty(input)) return null;
		return to16String(input.getBytes());
	}
	
	/**
	 * 功能：字符数组转16进制串
	 * @param bs
	 * @return
	 */
	public static String to16String(byte[] bs){
		if (bs==null||bs.length==0) return null;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < bs.length; i++) {
			String hex = Integer.toHexString(bs[i] & 0xFF);
			if (hex.length() == 1) { 
				hex = '0' + hex;
			} 
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}
	/**
	 * 功能:16进制串转字节数组
	 * @param input
	 * @return
	 */
	public static byte[] toBytesBy16String(String input){
		if (isEmpty(input)) return null;
		if (!isMatch(input, "^[\\dA-F]+$")) return null;
		if (input.length()%2==1) return null;
		byte[] bs = new byte[input.length()/2];
		for (int i = 0; i < input.length()/2; i++) {
			bs[i] = (byte) Integer.parseInt(input.substring(i*2, i*2+2),16);
		}
		return bs;
	}
	
	/**
	 * 功能:16进制串转正常字符串
	 * @param input
	 * @return
	 */
	public static String toStringBy16String(String input,String encoding){
		if (isEmpty(input)) return null;
		if (!isMatch(input, "^[\\dA-F]+$")) return null;
		if (input.length()%2==1) return null;
		try {
			return new String(toBytesBy16String(input),encoding);
		} catch (UnsupportedEncodingException e) {
			System.err.println(format("[16进制串转正常字符串失败!]参数:input.length()={0},encoding={1}", input.length()+"",encoding));
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 功能：生成一个唯一id
	 * @return
	 */
	public static String genUniqueId(){
		long lastTime = System.currentTimeMillis();
		StringBuffer result = new StringBuffer();
		result.append("UID");
		Random random = new Random(); 
		result.append(lastTime).append(uidCount++).append(random.nextInt(10000));
		return result.toString();
	}
	private static int uidCount=0; 
	
	public static void main(String[] args) {
//		for (int i = 0; i < 100; i++) {
//			System.out.println(genUniqueId());
//		}
//		System.out.println("1sdfas1".replaceAll("1", "\\w"));
//		System.out.println(toStringBy16String("3424243214","utf-8"));
		
//		String[] encodings = {"GBK","GB2312", "UTF-8", "UTF-16","BIG5",
//				"UTF-16BE", "UTF-16LE", "US-ASCII", "ISO-8859-1","ASCII","UNICODE"};
//		for (String encoding : encodings) {
//			try {
//				byte[] bs = "sdf颗地地畏惧 ".getBytes(encoding);
//				System.out.println(encoding+":"+new String(bs,encoding));
//			} catch (UnsupportedEncodingException e) {
//				e.printStackTrace();
//			}
//		}
		
		String input = "fffffffff#req00001#wwwwwwwwwwwwww";
		
		String re = "#(req00001)#";
		String req = "^[a-zA-Z]\\w{3,15}$";
		
//		System.out.println(req.replaceAll("\\$", "\\\\\\$"));
		System.out.println(input.replaceAll(re,req.replaceAll("\\$", "\\\\\\$") ));
		
	}
}
